import React, { Component, Fragment } from 'react';
import Css from "./index.module.scss"
import { PickerView } from "antd-mobile"
import { request } from "../../../utils/request"
import { connect } from "react-redux"
class Filter extends Component {
    // 标题数组
    state = {
        titles: [
            { id: 0, text: '区域', cols: 3 },
            { id: 1, text: '方式', cols: 1 },
            { id: 2, text: '租金', cols: 1 },
            { id: 3, text: '筛选', cols: -1 },
        ],
        currentIndex: -1,
        filterList: [],
        //筛选组件的值
        seleValList: [[], [], [], []]
    }
    async componentDidMount() {
        const cityName = this.props.cityName;
        console.log(cityName);
        // 定义筛选数组
        let filterList = [];
        // 根据城市名称拿到房子id
        const id = (await request.get('/area/info?name=' + cityName)).data.body.value;
        // 根据城市id拿到房源条件
        const res = (await request.get('/houses/condition?id=' + id)).data.body;
        console.log(res);
        //   第一个筛选组件的数据源
        filterList.push([
            res.area,
            res.subway
        ])
        // 第二个筛选条件的数据源
        filterList.push(res.rentType);
        // 第三个筛选条件的数据源
        filterList.push(res.price);
        // 第四个筛选条件的数据源
        filterList.push([
            { label: '户型', children: res.roomType },
            { label: '朝向', children: res.oriented },
            { label: '楼层', children: res.floor },
            { label: '房屋亮点', children: res.characteristic }
        ])

        // 更新视图数据
        this.setState({ filterList })


    }
    handleTitleClick = (i) => {
        this.setState({ currentIndex: i })
    }
    // 取消按钮
    handleCancel = () => {
        this.setState({ currentIndex: -1 });
    }
    // 筛选组件picker-view
    handleSeleChange = (selVal) => {
        console.log(selVal);
        let { seleValList, currentIndex } = this.state;
        seleValList[currentIndex] = selVal;
        this.setState({ seleValList });
        console.log(seleValList);

    }
    //第四个筛选组件的每一项
    handleMoreItemClick = (value) => {
        const { currentIndex, seleValList } = this.state;
        const index = seleValList[currentIndex].findIndex(v => v === value);
        if (index == -1) {
            // 不存在， 添加
            seleValList[currentIndex].push(value);
        } else {
            // 存在删除
            seleValList[currentIndex].splice(index, 1);
        }
        this.setState({ seleValList });
        console.log(seleValList);

    }
    // 点击确定按钮
    handleConfirm = () => {
        // 将数组组装成一个对象的格式
        // 对象的组装 属性名  属性值
        const { seleValList } = this.state;
        // 1.1获取第一个筛选组件的属性名
        let area_subway_name = seleValList[0][0];
        //  1.2获取属性值
        // 对数组的第三元素判断 如果 合法（不能是"null" undefined）,就拿第三个，不合法就拿第二个
        let area_subway_value = seleValList[0][2];
        area_subway_value = ['null', undefined].includes(area_subway_value) ? seleValList[0][1] : area_subway_value;

        // 2.1获取租房的方式的值
        const rentType = seleValList[1][0];
        // 3.1 获取租金的值
        const price = seleValList[2][0];
        // 4.1第四个筛选组件more
        const more = seleValList[3].join(',');

        // 构造参数对象
        // 对obj对象的属性名和属性值 做一个判断  只要不合法就删除该属性即可
        let obj = {
            [area_subway_name]: area_subway_value,
            rentType,
            price,
            more
        }
        // 对对象进行过滤，不合法（"null" undefined）
        for (const key in obj) {
            if (['', 'null', undefined].includes(obj[key])) {
                delete obj[key];
            }
        }
        // 子向父传递数据，通过自定义事件的方式进行传递
        this.props.onHandleSubmit(obj);
        //点击确定按钮之后，需要经筛选组件picker-view隐藏
        this.setState({ currentIndex: -1 });

    }
    // 清除第四个组件选中的值
    handleClearMore = () => {
        const { seleValList, currentIndex } = this.state;
        seleValList[currentIndex] = [];
        this.setState({ seleValList });

    }
    renderContent = () => {
        //   根据索引渲染不同的筛选组件
        const { currentIndex, filterList, titles, seleValList } = this.state;
        // 0-2
        if (!filterList.length) {
            return;
        }
        else if (currentIndex >= 0 && currentIndex <= 2) {
            return <div className={Css.filter_picker}>
                <PickerView data={filterList[currentIndex]} cols={titles[currentIndex].cols}
                    onChange={this.handleSeleChange} value={seleValList[currentIndex]} />
                {/* 两个按钮 */}
                <div className={Css.picker_tools}>
                    <span onClick={this.handleCancel.bind(this)}>取消</span>
                    <span onClick={this.handleConfirm}>确定</span>
                </div>
            </div>
        } else if (currentIndex === 3) {
            return <div className={Css.filter_more}>
                <div className={Css.filter_more_content}>
                    {filterList[currentIndex].map(v => <div key={v.label} className={Css.more_group}>
                        <div className={Css.more_group_title}>{v.label}</div>
                        <div className={Css.more_group_list}>{v.children.map(vv => <div className={[Css.more_item, seleValList[currentIndex].includes(vv.value) ? Css.active : ''].join(' ')} onClick={() => this.handleMoreItemClick(vv.value)} key={vv.value}>{vv.label}</div>)}</div>
                    </div>)}
                </div>
                {/*按钮 */}
                <div className={Css.filter_more_tools}>
                    <span onClick={this.handleClearMore}>清除</span>
                    <span onClick={this.handleConfirm}>确定</span>
                </div>
            </div >
        } else {
            return <></>

        }
    }
    render() {
        const { titles, currentIndex } = this.state;
        return <div className={Css.filter}>
            <div className={Css.filter_view}>
                {/* 标题开始 */}
                <div className={[Css.filter_title, currentIndex === 3 ? Css.z100 : ''].join(" ")}>
                    {titles.map((v, i) => <div key={v.id} onClick={() => this.handleTitleClick(i)} className={[Css.title_item, currentIndex === i ? Css.active : ''].join(' ')}>
                        {v.text}
                    </div>)}
                    {/* 标题结束 */}
                </div>
                {/* 标题结束 */}
                {/* 内容开始 */}
                <div className={Css.picker_content}>
                    {/* 内容开始 */}
                    {this.renderContent()}
                </div>
                {/* 内容结束 */}
                {/* 遮罩层 开始 */}
                <div className={Css.mask} onClick={this.handleCancel} hidden={currentIndex === -1}></div>
                {/* 遮罩层 结束 */}
            </div>

        </div>

    }
}
const mapStateToProps = (state) => ({
    cityName: state.CityReducer.cityname.name
})
export default connect(mapStateToProps)(Filter);